package cn.gemiman.daoyi.module.system.controller.app.tenant;

import cn.gemiman.daoyi.framework.common.pojo.CommonResult;
import cn.gemiman.daoyi.framework.common.util.object.BeanUtils;
import cn.gemiman.daoyi.framework.common.util.servlet.ServletUtils;
import cn.gemiman.daoyi.module.system.controller.admin.tenant.vo.tenant.TenantSimpleRespVO;
import cn.gemiman.daoyi.module.system.dal.dataobject.tenant.TenantDO;
import cn.gemiman.daoyi.module.system.service.tenant.TenantService;
import cn.hutool.core.text.CharSequenceUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import static cn.gemiman.daoyi.framework.common.pojo.CommonResult.error;
import static cn.gemiman.daoyi.framework.common.pojo.CommonResult.success;
import static cn.gemiman.daoyi.module.system.enums.ErrorCodeConstants.TENANT_NOT_EXISTS;
import static cn.gemiman.daoyi.module.system.enums.ErrorCodeConstants.TENANT_WEBSITE_REQUIRED;

@Tag(name = "用户 APP - 租户")
@RestController
@RequestMapping("/system/tenant")
public class AppTenantController {

    @Resource
    private TenantService tenantService;

    @GetMapping("/get-id-by-name")
    @Operation(summary = "使用租户名，获得租户编号", description = "登录界面，根据用户的租户名，获得租户编号")
    @Parameter(name = "name", description = "租户名", required = true, example = "1024")
    public CommonResult<Long> getTenantIdByName(@RequestParam("name") String name) {
        TenantDO tenant = tenantService.getTenantByName(name);
        if (null == tenant) {
            return error(TENANT_NOT_EXISTS);
        }
        return success(tenant.getId());
    }

    @GetMapping("/get-by-website")
    @Operation(summary = "使用域名，获得租户信息", description = "登录界面，根据用户的域名，获得租户信息")
    @Parameter(name = "website", description = "域名", required = true, example = "www.iocoder.cn")
    public CommonResult<TenantSimpleRespVO> getTenantByWebsite(@RequestParam(value = "website", required = false) String website) {
        if (CharSequenceUtil.isBlank(website)) {
            website = ServletUtils.getClientDomain();
        }
        if (CharSequenceUtil.isBlank(website)) {
            return error(TENANT_WEBSITE_REQUIRED);
        }
        TenantDO tenant = tenantService.getTenantByWebsite(website);
        if (null == tenant) {
            return error(TENANT_NOT_EXISTS);
        }
        return success(BeanUtils.toBean(tenant, TenantSimpleRespVO.class));
    }

}
